import { defineStore } from 'pinia'
import { ref } from 'vue'
import { request } from '@/utils/request'
import type { WorkflowData } from '@/types/workflow'

export const useWorkflowStore = defineStore('workflow', () => {
    const workflows = ref<WorkflowData[]>([])
    const loading = ref(false)

    // 创建工作流
    const createWorkflow = async (data: Partial<WorkflowData>) => {
        try {
            // 验证必要字段
            if (!data.name || !data.title || !data.type) {
                throw new Error('请填写必要的工作流信息')
            }

            // 确保 workflow 和 template 是字符串
            const workflowData = {
                ...data,
                workflow: typeof data.workflow === 'string' ? data.workflow : JSON.stringify(data.workflow || {}),
                template: typeof data.template === 'string' ? data.template : JSON.stringify(data.template || {
                    version: '1.0.0',
                    params: [],
                    layout: { groups: [] }
                })
            }

            console.log('Sending workflow data:', workflowData)

            const response = await request.post('/api/workflows', workflowData)
            return response
        } catch (error) {
            console.error('Failed to create workflow:', error)
            throw error
        }
    }

    // 更新工作流
    const updateWorkflow = async (id: string, data: Partial<WorkflowData>) => {
        try {
            const workflowData = {
                ...data,
                workflow: typeof data.workflow === 'string' ? data.workflow : JSON.stringify(data.workflow || {}),
                template: typeof data.template === 'string' ? data.template : JSON.stringify(data.template || {})
            }

            const response = await request.put(`/api/workflows/${id}`, workflowData)
            return response
        } catch (error) {
            console.error('Failed to update workflow:', error)
            throw new Error('更新工作流失败')
        }
    }

    // 获取工作流列表
    const getWorkflows = async (params?: Record<string, any>) => {
        try {
            loading.value = true
            const response = await request.get('/api/workflows', { params })
            return {
                items: response.items || [],
                total: response.total || 0
            }
        } finally {
            loading.value = false
        }
    }

    // 获取工作流详情
    const getWorkflow = async (id: string) => {
        const response = await request.get(`/api/workflows/${id}`)
        return response
    }

    // 删除工作流
    const deleteWorkflow = async (id: string) => {
        try {
            await request.delete(`/api/workflows/${id}`)
        } catch (error) {
            console.error('Failed to delete workflow:', error)
            throw new Error('删除工作流失败')
        }
    }

    return {
        workflows,
        createWorkflow,
        updateWorkflow,
        getWorkflows,
        getWorkflow,
        deleteWorkflow
    }
})